package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.impl.CategoryServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/category")
public class CategoryController {


    @Autowired
    private CategoryServiceImpl categoryService;

    /**
     * 分页搜索
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        //分页
        Page page1 = new Page(page, pageSize);
        // 构建条件搜索
        LambdaQueryWrapper law = new LambdaQueryWrapper();
        law.orderByDesc();
        categoryService.page(page1, law);

        return R.success(page1);
    }

    /**
     * 添加菜品
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);

        return R.success("添加成功");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleCategory(Long id) {
        LambdaQueryWrapper lqw = new LambdaQueryWrapper();
        categoryService.remove(id);

        return R.success("删除成功");
    }


    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("成功");
    }

    /**
     *  根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>>list(Category category) {
        // 条件搜索构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        // 添加条件
         lqw.eq(category.getType() != null, Category::getType, category.getType());
         //添加排序条件
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //  查出数据
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
    // 在CategoryController中增加方法实现菜品分类查询，根据分类进行查询，
    // 并对查询的结果按照sort排序字段进行升序排序，如果sort相同，再按照修改时间倒序排序。



}